<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/4 0004
 * Time: 09:30
 */

namespace app\admin\controller;


use think\Db;
use app\admin\model\Config as ConfigModel;

class Config extends Base
{
    const TABLE_CONFIG = 'config';

    public function index()
    {
        return $this->fetch();
    }

    public function web()
    {
        $this->assign('action',url('web'));
        $this->assign('title','网站设置');
        return $this->baseConfig(1);
    }

    public function sys()
    {
        $this->assign('action',url('sys'));
        $this->assign('title','系统设置');
        return $this->baseConfig(2);
    }

    private function baseConfig($group=1)
    {
        if(request()->isPost()){
            $param = input();
            foreach ($param['data'] as $k=>$v)
            {
                Db::name(self::TABLE_CONFIG)->where('name',$k)->update(['value'=>$v]);
            }
            $res = $this->saveConfig();
            if ($res !== false) {
                return $this->success ( '参数设置成功！' );
            } else {
                return $this->error ( '操作失败！' );
            }
        }
        $data = ConfigModel::get_list($group);
        foreach ($data as &$value)
        {
            if($value->type == 'select' || $value->type == 'radio'){
                $value->option = [];
                $option = explode(',',$value->extra);
                foreach ($option as &$v)
                {
                    $v = explode(':',$v);
                }
                $value->option = $option;
            }
        }
        $this->assign('data',$data);
        return $this->fetch('index');
    }


    private function saveConfig()
    {
        $config = Db::name(self::TABLE_CONFIG)->where('status',1)->select();
        foreach ($config as $v)
        {
            $data[$v['name']] = $v['value'];
        }
        //生成配置文件
        $config_file = APP_PATH . 'extra/setting.php';
        create_file ( $config_file );
        arr2file ( $config_file, $data );
    }
}